package com.Yukiha.gachamod.network;

import com.Yukiha.gachamod.gachaMenu.client.ClientGachaDataCache;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;

import java.util.*;
import java.util.function.Supplier;

public class SyncGachaModelsPacket {
    public final Map<String, Set<String>> modelMap;

    public SyncGachaModelsPacket(Map<String, Set<String>> modelMap) {
        this.modelMap = modelMap;
    }

    public static void encode(SyncGachaModelsPacket msg, FriendlyByteBuf buf) {
        buf.writeInt(msg.modelMap.size());
        for (Map.Entry<String, Set<String>> entry : msg.modelMap.entrySet()) {
            buf.writeUtf(entry.getKey()); // 稀有度
            buf.writeInt(entry.getValue().size());
            for (String model : entry.getValue()) {
                buf.writeUtf(model);
            }
        }
    }

    public static SyncGachaModelsPacket decode(FriendlyByteBuf buf) {
        int rarityCount = buf.readInt();
        Map<String, Set<String>> map = new HashMap<>();

        for (int i = 0; i < rarityCount; i++) {
            String rarity = buf.readUtf();
            int modelCount = buf.readInt();
            Set<String> models = new HashSet<>();
            for (int j = 0; j < modelCount; j++) {
                models.add(buf.readUtf());
            }
            map.put(rarity, models);
        }

        return new SyncGachaModelsPacket(map);
    }

    public static void handle(SyncGachaModelsPacket msg, Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> {
            ClientGachaDataCache.updateFromServer(msg.modelMap); // ✅ 现在匹配上了
        });
        ctx.get().setPacketHandled(true);
    }
}
